import localStore from 'store';
import jwt from 'jsonwebtoken';
import cookiejs from 'cookiejs';
import { storage } from '@/plugins/storage';

export const SUBMIT_TOKEN = 'unique-submit-token';

export const setSubmitToken = (token) => {
  if (!token) return;
  storage.set(SUBMIT_TOKEN, token);
  // 与其它应用共享一份 SUBMIT_TOKEN
  localStore.set(SUBMIT_TOKEN, token);
};

export const getSubmitToken = () => {
  return storage.get(SUBMIT_TOKEN) || '';
};

export const clearSubmitToken = () => {
  storage.remove(SUBMIT_TOKEN);
};

export const getUserToken = () => {
  return storage.get('user_token') || cookiejs.get('access_token');
};

export const getUserPayload = () => {
  const token = getUserToken();
  if (token) {
    const payload = jwt.decode(token, { json: true });
    return {
      ...payload,
      // NOTE: payload .exp 是秒为单位
      expired: payload?.exp && payload?.exp * 1000 < Date.now(),
    };
  }
  return {
    expired: true,
  };
};

export const setUserToken = (token) => {
  storage.set('user_token', token);
};
